package com.wissen.temperatureapp.client.widgets;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.wissen.temperatureapp.client.controller.TempController;
import com.wissen.temperatureapp.client.observers.TemperatureObserver;

/**
 * Class represents a celsius widget. Provides celsius UI for user.
 * 
 * @author Mayur Birari
 * 
 */
public class CelsiusWidget  extends Composite implements TemperatureObserver {

    private HorizontalPanel celsiusPanel;

    private TextBox         celsiusTextBox;

    private FlexTable       celsiusTable;

    private Button          celsiusButton;

    public CelsiusWidget() {
        init();

        celsiusPanel.add(celsiusTable);

        celsiusButton.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                convertTemp();   
            }
        });

        initWidget(celsiusPanel);
    }

    private void init() {
    	celsiusPanel = new HorizontalPanel();
    	celsiusTextBox = new TextBox();        
    	celsiusButton = new Button("Converter");

        //creating table
    	celsiusTable = new FlexTable();
    	celsiusTable.setText(1, 0, "Celsius Value: ");
    	celsiusTable.setWidget(1, 1, celsiusTextBox);
    	celsiusTable.setWidget(2, 0, celsiusButton);
    	celsiusTable.getFlexCellFormatter().setColSpan(2, 0, 2);
    	celsiusTable.getFlexCellFormatter().setAlignment(3, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE);
    }

    /**
     * Method convert celsius into Fahrenheit.
     * 
     * */
    private void convertTemp() {
        TempController.getInstance().convertTemp(Double.parseDouble(celsiusTextBox.getText()));
    }
    
    
    public void notifyConvertFailed(String errorMessage) {
        Window.alert("Conversion fail: " + errorMessage);
    }
    
    public void notifyConvertSucceeded(Double celsiusvalue) {
    	celsiusTextBox.setText(celsiusvalue.toString());
    }
}
